package com.fowo.api.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.fowo.api.entity.*;
import com.fowo.api.mapper.*;
import com.fowo.api.model.nav.sell.order.NavSellOrderVo;
import com.fowo.api.model.nav.sell.order.declare.NavSellOrderDeclareItemVo;
import com.fowo.api.model.nav.sell.order.detail.NavSellOrderDetailItemVo;
import com.fowo.api.model.nav.sell.order.platform.NavSellOrderPlatformItemVo;
import com.fowo.api.model.nav.sell.order.transaction.NavSellOrderTransactionItemVo;
import com.fowo.api.service.NavSellOrderCreateService;
import com.fowo.api.service.NavSellOrderPlatformService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class NavSellOrderCreateServiceImpl implements NavSellOrderCreateService {

    @Resource
    private NavSellOrderPlatformMapper navSellOrderPlatformMapper;
    @Resource
    private NavSellOrderMapper navSellOrderMapper;
    @Resource
    private NavSellOrderDetailServiceImpl navSellOrderDetailService;
    @Resource
    private NavSellOrderTransactionServiceImpl navSellOrderTransactionService;
    @Resource
    private NavSellOrderDeclareServiceImpl navSellOrderDeclareService;
    @Resource
    private NavSellOrderPlatformServiceImpl navSellOrderPlatformService;
    @Resource
    private SysCountryMapper sysCountryMapper;

    private static Map<String, List<SysCountry>> countryMap = null;

    private final IdentifierGenerator identifierGenerator = new DefaultIdentifierGenerator();

    @Override
    public String getType(Long id) {
        QueryWrapper<NavSellOrderPlatform> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_nav_sell_order",id);
        List<NavSellOrderPlatform> navSellOrderPlatforms = navSellOrderPlatformMapper.selectList(queryWrapper);
        if(navSellOrderPlatforms != null && navSellOrderPlatforms.size() > 0){
            return navSellOrderPlatforms.get(0).getPlatform();
        }
        return null;
    }

    @Override
    public NavSellOrderVo create(NavSellOrderVo navSellOrderVo) {
        //主表数据入库 获取主表id
        NavSellOrder order = new NavSellOrder();
        BeanUtils.copyProperties(navSellOrderVo,order);
        int insert = navSellOrderMapper.insert(order);
        List<NavSellOrderDetail> details = new ArrayList<>();
        List<NavSellOrderTransaction> transactions = new ArrayList<>();
        List<NavSellOrderDeclare> declares = new ArrayList<>();
        List<NavSellOrderPlatform> platforms = new ArrayList<>();
        if(insert > 0){
            //明细数据绑定主表id 入库
            List<NavSellOrderPlatformItemVo> platform = navSellOrderVo.getPlatform();
            for (NavSellOrderPlatformItemVo itemVo : platform) {
                NavSellOrderPlatform platform1 = new NavSellOrderPlatform();
                BeanUtils.copyProperties(itemVo,platform1);
                platform1.setParentNavSellOrder(order.getId());
                platforms.add(platform1);
            }
            for (NavSellOrderDetailItemVo orderDetail:navSellOrderVo.getProduct()) {
                NavSellOrderDetail detail = new NavSellOrderDetail();
                BeanUtils.copyProperties(orderDetail,detail);
                detail.setParentNavSellOrder(order.getId());
                details.add(detail);
            }
            for (NavSellOrderTransactionItemVo orderTransaction:navSellOrderVo.getTransaction()) {
                NavSellOrderTransaction transaction = new NavSellOrderTransaction();
                BeanUtils.copyProperties(orderTransaction,transaction);
                transaction.setParentNavSellOrder(order.getId());
                transactions.add(transaction);
            }
            for (NavSellOrderDeclareItemVo orderDeclare:navSellOrderVo.getDeclare()) {
                NavSellOrderDeclare declare = new NavSellOrderDeclare();
                BeanUtils.copyProperties(orderDeclare,declare);
                declare.setParentNavSellOrder(order.getId());
                declares.add(declare);
            }
            if(details.size() > 0){
                navSellOrderDetailService.saveBatch(details);
                navSellOrderPlatformService.saveBatch(platforms);
                navSellOrderTransactionService.saveBatch(transactions);
                navSellOrderDeclareService.saveBatch(declares);
            }
        }
        return null;
    }

    @Override
    public NavSellOrderVo dataPackage(Integer type, JSONObject data) {
        switch (type){
            case 0:
                return AmazonData(data);
            case 1:
                return walmartData(data);
            case 2:
                return sheinData(data);
            case 3:
                return null;
        }
        return null;
    }

    /**
     * 获取所有国家
     * @return
     */
    public void getCountry() {
        QueryWrapper<SysCountry> queryWrapper = new QueryWrapper();
        queryWrapper.isNotNull("code");
        List<SysCountry> sysCountries = sysCountryMapper.selectList(queryWrapper);
        countryMap = sysCountries.stream().collect(Collectors.groupingBy(SysCountry::getCode));
    }

    /**
     * 组装亚马逊数据
     * @param data
     * @return
     */
    private NavSellOrderVo AmazonData(JSONObject data){
        NavSellOrderVo navSellOrderVo = new NavSellOrderVo();

        return navSellOrderVo;
    }

    /**
     * 组装沃尔玛数据
     * @param data
     * @return
     */
    private NavSellOrderVo walmartData(JSONObject data){
        NavSellOrderVo navSellOrderVo = new NavSellOrderVo();
        JSONArray order = data.getJSONArray("order");
        List<NavSellOrder> list = new ArrayList<>();
        List<NavSellOrderDetail> detailList = new ArrayList<>();
        List<NavSellOrderPlatform> platFormList = new ArrayList<>();
        List<NavSellOrderTransaction> transactionList = new ArrayList<>();
        for (Object object:order) {
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            NavSellOrder sellOrder = new NavSellOrder();
            Long aLong = (Long) identifierGenerator.nextId(null);
            sellOrder.setId(aLong);
            sellOrder.setBuyerEmail(jsonObject.get("customerEmailId").toString());
            sellOrder.setCreateTime(new Date());
            //表结构改变 订单来源存储位置更换
            NavSellOrderPlatform navSellOrderPlatform = new NavSellOrderPlatform();
            navSellOrderPlatform.setPurchaseTime(DateUtil.date(Long.parseLong(jsonObject.getString("orderDate"))));
            navSellOrderPlatform.setSource("1");
            navSellOrderPlatform.setPlatform("Walmart");
            navSellOrderPlatform.setParentNavSellOrder(aLong);
            //获取物流信息
            JSONObject address = JSONObject.parseObject(jsonObject.get("shippingInfo").toString());
            sellOrder.setDeliveryPhone(address.getString("phone"));
            JSONObject postalAddress = address.getObject("postalAddress", JSONObject.class);
            sellOrder.setDeliveryCity(postalAddress.getString("city"));
            List<SysCountry> sysCountries1 = countryMap.get(postalAddress.getString("country").equals("USA") ? "US" : postalAddress.getString("country"));
            if(sysCountries1 != null && sysCountries1.size() > 0){
                sellOrder.setDeliveryCountry(sysCountries1.get(0).getId());
            }
            sellOrder.setDeliveryAddressType(postalAddress.getString("addressType"));
            sellOrder.setDeliveryAddress1(postalAddress.getString("address1"));
            sellOrder.setDeliveryZipCode(postalAddress.getString("postalCode"));

            JSONObject orderLines = JSONObject.parseObject(jsonObject.get("orderLines").toString());
            JSONArray objects = JSONObject.parseArray(orderLines.get("orderLine").toString());
            sellOrder.setDeliveryRealQuantity(objects.size());

            //商品信息
            //总价
            BigDecimal decimal = BigDecimal.ZERO;
            BigDecimal taxTotal = BigDecimal.ZERO;
            double weight = 0.00;
            List<NavSellOrderDetail> details = new ArrayList<>();
            String status = "";
            for (Object o:objects) {
                JSONObject line = JSONObject.parseObject(o.toString());
                //获取订单状态
                JSONObject orderLineStatuses = line.getObject("orderLineStatuses", JSONObject.class);
                JSONArray orderLineStatus = orderLineStatuses.getJSONArray("orderLineStatus");
                if(orderLineStatus != null && orderLineStatus.size() > 0){
                    JSONObject jsonObject1 = JSONObject.parseObject(orderLineStatus.get(0).toString());
                    String string = jsonObject1.getString("status");
                    status = string;
                }

                NavSellOrderDetail detail = new NavSellOrderDetail();
                detail.setCreateTime(new Date());
                detail.setId((Long) identifierGenerator.nextId(null));
                detail.setParentNavSellOrder(aLong);
                JSONObject item = line.getObject("item", JSONObject.class);
                detail.setSku(item.getString("sku"));
                detail.setProductName(item.getString("productName"));
                //判断重量是否为空 转换为克存储
                JSONObject weight1 = item.getObject(("weight"), JSONObject.class);
                if(weight1 != null){
                    if(weight1.getString("unit").equals("Pounds")){
                        weight = weight + Double.valueOf(weight1.getString("value")) * 453.59237;
                    }
                }

                JSONObject charges = line.getObject("charges", JSONObject.class);
                //价格
                JSONArray charge = charges.getJSONArray("charge");
                JSONObject charge1 = JSONObject.parseObject(charge.get(0).toString());
                JSONObject chargeAmount = charge1.getObject("chargeAmount", JSONObject.class);
                if(chargeAmount != null){
                    if(chargeAmount.getBigDecimal("amount") != null){
                        detail.setPrice(chargeAmount.getBigDecimal("amount"));
                        decimal = decimal.add(chargeAmount.getBigDecimal("amount"));
                    }
                }
                //税费
                JSONObject tax = charge1.getObject("tax", JSONObject.class);
                if(tax != null){
                    BigDecimal amount = tax.getBigDecimal("amount");
                    if(amount != null){
                        taxTotal = taxTotal.add(amount);
                    }
                }
                detailList.add(detail);
            }
            NavSellOrderTransaction transaction = new NavSellOrderTransaction();
            transaction.setTax(taxTotal);
//            transaction.setTradeAmount(decimal);
            transaction.setTotalAmount(decimal);
            transaction.setParentNavSellOrder(aLong);

            sellOrder.setStatus("1");
            sellOrder.setDeliveryRealWeight(BigDecimal.valueOf(weight));
            list.add(sellOrder);
            transactionList.add(transaction);
            platFormList.add(navSellOrderPlatform);
        }
        return navSellOrderVo;
    }

    /**
     * 组装希音数据
     * @param data
     * @return
     */
    private NavSellOrderVo sheinData(JSONObject data){
        NavSellOrderVo navSellOrderVo = new NavSellOrderVo();

        return navSellOrderVo;
    }
}
